<script>
// import previewVue from '../preview.vue';
import Api from '@/services/commonApi'
import Success from '@/pages/components/Result'
import _ from 'lodash'
export default {
  data() {
    return {
      formData: [],
      ruleForm: {},
      tFormData: {},
      rules: {},
      fileList: [],
      uploading: false,
      end: false
      // isPc: false
    }
  },
  props: {
    templateData: {
      type: Object
    },
    isPc: {
      type: Boolean,
      default: true
    },
    answers: {
      type: Array,
      default: () => []
    }
  },
  created() {
    this.tFormData = this.templateData
    this.dealRuleForm(this.templateData);
  },
  components: {
    'q-success': Success
  },
  methods: {

    /**
     * @Description: 渲染表单函数
     * @param {*}
     * @Date: 2020-10-29 15:02:02
     */    
    renderForm() {
      const { formData } = this
      return (
        <a-form-model 
          ref="questionnaireForm"
          {...{props: {
              model: this.ruleForm,////vue jsx element 表单校验的model不可以直接写 以这种方式解决
              rules: this.rules
          } } }
        >
          {
            ...formData.map((item) => {
              return (
                <a-form-model-item 
                  key={item.id} 
                  prop={item.id} 
                  colon={false} 
                  label={item.headerNumber + '. ' + item.headerName}
                  rules={item.rules}
                >
                  {this.typeMapFormItem(item)}
                </a-form-model-item>
              )
            })
          }
          {
            this.answers.length ? null : 
            <a-form-model-item >
              <a-button type="primary" onClick={() => this.submitForm('questionnaireForm')}>
                提交
              </a-button>
              <a-button style="margin-left: 10px;" onClick={this.handleCancle}>
                取消
              </a-button>
            </a-form-model-item>
          }
          
        </a-form-model>
      );
    },

    /**
     * @Description: 渲染表单子组件
     * @param {*} item
     * @Date: 2020-10-29 15:02:13
     */    
    typeMapFormItem(item) {
      switch(item.formType) {
        case 1:
          return <a-radio-group v-model={this.ruleForm[item.id]} disabled={this.answers.length > 0}>
                  {
                    ...item.configDtos.map(it => {
                      return (
                        <a-radio value={it.configNumber} style="display: block;height: 28px">
                          {it.configName}
                        </a-radio>
                      );
                    })
                  }
                </a-radio-group>
        case 2:
          return <a-checkbox-group v-model={this.ruleForm[item.id]} disabled={this.answers.length > 0}>
                  {
                    ...item.configDtos.map(it => {
                      return (
                        <a-checkbox value={it.configNumber}>
                          {it.configName}
                        </a-checkbox>
                      );
                    })
                  }
                </a-checkbox-group>
        case 3:
          return <a-select v-model={this.ruleForm[item.id]} style="max-width: 300px" disabled={this.answers.length > 0}>
                    {
                      ...item.configDtos.map(it => {
                        return (
                          <a-select-option value={it.configNumber} style="display: block;height: 28px;">
                            {it.configName}
                          </a-select-option>
                        );
                      })
                    }
                  </a-select>
        case 4:
          return <a-input
                    style="max-width: 300px"
                    v-model={this.ruleForm[item.id]}
                    disabled={this.answers.length > 0}
                  />
        case 100:
          return <a-input
                    style="max-width: 300px"
                    v-model={this.ruleForm[item.id]}
                    disabled={this.answers.length > 0}
                  />
        case 101:
          return <a-radio-group v-model={this.ruleForm[item.id]} disabled={this.answers.length > 0}>
                  {
                    ...item.configDtos.map(it => {
                      return (
                        <a-radio value={it.configNumber} style="display: block;height: 28px;">
                          {it.configName}
                        </a-radio>
                      );
                    })
                  }
                </a-radio-group>
        case 102:
          return <a-radio-group v-model={this.ruleForm[item.id]} disabled={this.answers.length > 0}>
                  {
                    ...item.configDtos.map(it => {
                      return (
                        <a-radio value={it.configNumber} style="display: block;height: 28px;">
                          {it.configName}
                        </a-radio>
                      );
                    })
                  }
                </a-radio-group>
        case 103:
          return <a-range-picker v-model={this.ruleForm[item.id]} disabled={this.answers.length > 0}/>
        case 200:
          return  <div class="clearfix">
                    <a-upload fileList={this.fileList} remove={this.handleRemove} beforeUpload={this.beforeUpload}>
                      <a-button> <a-icon type="upload" /> 选择文件 </a-button>
                    </a-upload>
                  </div>
        default:
          break;
      }
      return null
    },
    
    /**
     * @Description: 提交
     * @param {*} formName
     * @Date: 2020-10-29 15:02:32
     */    
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.createForm()
        } else {
          return false;
        }
      });
    },

    /**
     * @Description: 处理ruleForm
     * @param {*}
     * @Date: 2020-10-29 15:02:47
     */    
    dealRuleForm(data) {
        data.headerDtos.forEach(item => {
          this.$set(this.ruleForm, item.id, null )
        })
        this.formData = data.headerDtos
        this.transformOptionToRules(data.headerDtos)
        if(this.answers.length) {
          this.setFormAnswer()
        }
    },

    /**
     * @Description: 设置表单答案
     * @param {*}
     * @Date: 2020-11-10 17:08:22
     */    
    setFormAnswer() {
      const {ruleForm} = this
      this.answers.forEach(answer => {
        ruleForm[answer.headerId] = JSON.parse(answer.answerName)
      })
      this.ruleForm = ruleForm
    },

    /**
     * @Description: 提交表单
     * @param {*}
     * @Date: 2020-11-03 09:27:44
     */    
    createForm() {
      const params = this.delaResult()
      Api.post('app/center/inner/answer/addAnswer', params).then(() => {
        this.end = true
      })
    },

    /**
     * @Description: 处理答案
     * @param {*}
     * @Date: 2020-11-10 17:07:02
     */    
    delaResult() {
      let result = {templateId: this.templateData.id, answerDtoList: []}
      this.templateData.userId ? result.userId = this.templateData.userId : null
      result.answerDtoList = Object.keys(this.ruleForm).map(key => {
        return {
          headerId: key,
          answerName: JSON.stringify(this.ruleForm[key]),
        }
      })
      return result
    },

    handleCancle() {
      this.end = true
    },

    /**
     * @Description: 规则配置转化为form表达可识别的rule规则
     * @param {*}
     * @Date: 2020-10-30 11:23:23
     */    
    transformOptionToRules(value) {
      let rules = {}
      value.forEach(item => {
        item.id = item.id + ''
        rules[item.id] = []
        if(!_.isEmpty(item.ruleOption)) {
          rules[item.id] = this.getRuleArray(item.ruleOption)
        } else {
          item.formType !== 200 ? rules[item.id] = [{required: true, message: '此项为必答项', trigger: item.formType === 4 ? 'blur' : 'change'}] : rules[item.id] = []
        }
      })
      this.rules = rules
    },

    /**
     * @Description: 根据ruleOption生成rule数组
     * @param {*}
     * @Date: 2020-10-30 11:32:09
     */    
    getRuleArray(options) {
      return Object.keys(options).map(key => {
        if(key === 'required' && options[key]) {
          return {required: true, message: '此项为必答项', trigger: options[key].formType === 4 ? 'blur' : 'change'}
        } else if (key === 'minValue') {
          return {
            min: options[key],
            message: `长度应该大于${options[key]}`,
            trigger: 'blur' 
          }
        } else if(key === 'maxValue') {
          return {
            max: options[key],
            message: `长度应该小于${options[key]}`,
            trigger: 'blur' 
          }
        } else if(key === 'formatLimit') {
          return {
            type: options[key],
            message: '请填写正确格式'
          }
        }
      })
    },

    /**
     * @Description: 删除
     * @param {*} file
     * @Date: 2020-11-02 09:55:28
     */    
    handleRemove(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
    },

    /**
     * @Description: 上传之前
     * @param {*} file
     * @Date: 2020-11-02 09:55:33
     */    
    beforeUpload(file) {
      this.fileList = [...this.fileList, file];
      return false;
    },

     /**
      * @Description: 文件上传逻辑
      * @param {*}
      * @Date: 2020-11-02 09:56:01
      */     
     handleUpload() {
      const { fileList } = this;
      const formData = new FormData();
      fileList.forEach(file => {
        formData.append('files[]', file);
      });
      this.uploading = true;

      // You can use any AJAX library you like
      // reqwest({
      //   url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
      //   method: 'post',
      //   processData: false,
      //   data: formData,
      //   success: () => {
      //     this.fileList = [];
      //     this.uploading = false;
      //     this.$message.success('upload successfully.');
      //   },
      //   error: () => {
      //     this.uploading = false;
      //     this.$message.error('upload failed.');
      //   },
      // });
    },

  },
  render() {
    return(
      <div id={this.isPc ? 'questionnaire-pc-preview': 'questionnaire-iphone-preview'}>
      {
        this.end 
        ? 
        <q-success style="margin-top: 30px" isSuccess={true} title={'答题结束'} description={'谢谢您的参与和配合'}></q-success>
        : <div class="preview-warp">
            <div class="title">
              <h3>{this.tFormData.titleName}</h3>
              <span>{this.tFormData.headline}</span>
            </div>
            <div>
              {this.renderForm()}
            </div>
          </div>
      }
      </div>
    );
  }
}
</script>

<style lang="less">
  #questionnaire-pc-preview {
    max-width: 90%;
    min-width: 300px;
    margin: 0 auto;
    background-color: #eee;
    min-height: 80vh;
    margin-top: 20px;
    padding: 20px;
    .preview-warp {
      width: 100%;
      height: 100%;
      .title {
        padding-bottom: 10px;
        border-bottom: 2px solid #53a4f4;
      }
    }
  }
  #questionnaire-iphone-preview {
    width: 372px;
    height: 744px;
    padding-top: 74px;
    margin: 0 auto;
    background-image: url(https://s1.wenjuan.com/static/images/Exterior_style/appearset_v3/appearset_bgc_big.png!90q.webp);
    background-size: 372px 744px;
    .preview-warp {
      width: 318px;
      height: 568px;
      overflow: scroll;
      margin: 0 auto;
      padding: 10px;
      background-color: #fff;
      .title {
        padding-bottom: 10px;
        border-bottom: 2px solid #53a4f4;
        
      }
    }
    
  }
</style>